﻿
using System;
using System.Diagnostics;
using AppFx.BizTalk.Container.Config;
using AppFx.BizTalk.Container.Loaders;


namespace AppFx.BizTalk.Container
{
    public class BizTalkApplicationContainer : ApplicationContainer
    {        
        private readonly string _applicationName;
        private string _loaderKey;
        private string _loaderType;

        public BizTalkApplicationContainer(string applicationName, string loaderType, string loaderKey)
        {
            Debug.Assert(string.IsNullOrEmpty(applicationName) == false, "The application name is not populated");
            _applicationName = applicationName;

            _loaderKey = loaderKey;
            _loaderType = loaderType;
            LoadContainer();
        } 

        public BizTalkApplicationContainer(string applicationName)
        {
            Debug.Assert(string.IsNullOrEmpty(applicationName) == false, "The application name is not populated");
            _applicationName = applicationName;

            GetConfig();
            LoadContainer();
        } 
       
        private void GetConfig()
        {
            var containerConfig = ContainerConfig.Current.Containers[_applicationName];
            if (containerConfig == null)
            {
                //TODO: Change this to just log?
                throw new ApplicationException(string.Format("There is no configuration for the container - {0}",
                    _applicationName));
            }
            _loaderType = containerConfig.LoaderType;
            _loaderKey = containerConfig.LoaderKey;
        }

        private void LoadContainer()
        {
            var containerLoader = GetLoader(_loaderType, _loaderKey);
            if(containerLoader != null)
                containerLoader.Load(ContainerBuilder, _loaderKey);
            
            BuildContainer();            
        }

        public IContainerLoader GetLoader(string loaderType, string loaderKey)
        {            
            switch (loaderType.ToUpper())
            {
                case "BRE":
                    return new BreLoader();
                case "CONFIG":
                    return new ConfigLoader();
                case "CUSTOM":
                    return new CustomTypeContainerLoader();
                case "NONE":
                    return null;
                default:
                    throw new ApplicationException(string.Format("Invalid loader type - {0}",
                    _applicationName));
            }
        }
    }
}
